﻿using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;

namespace MegaSetting
{
    //[Serializable]
    //Database db=new Database();
    static class Utility
    {


        static Database db;
        public static PointSetting Setting{get;set;}
        static readonly string DATABASE_PATH = Application.StartupPath + @"\MegaSetting.db";
        static readonly string SETTINGS_PATH = @"D:\SBK\Backup\Point.setting";
        //临时绑定列表 存储按区县筛选的网点
        static BindingList<Point> blistTmp = new BindingList<Point>();
        static Utility()
        {

            //判断数据文件是否存在
            if (File.Exists(DATABASE_PATH))
            {
                LoadDatabase();
            }
            //未找到数据库文件，创建空对象
            else
            {
                db = new Database();
            }

            //判断用户设置是否存在
            if (File.Exists(SETTINGS_PATH))
            {
                LoadLocalSettings();
            }
            else
            {
                Setting = new PointSetting();
            }

            db.districts.AllowEdit = true;
            db.districts.AllowNew = true;
            db.districts.AllowRemove = true;

            db.servers.AllowEdit = false;
            db.servers.AllowNew = false;
            db.servers.AllowRemove = false;

            db.districts.AddingNew += new AddingNewEventHandler(Utility_AddingNew);
            //db.servers.AddingNew += new AddingNewEventHandler(Utility_AddingNew);

            //db.points.Values.AddingNew+=new AddingNewEventHandler(Utility_AddingNew);

            //districts.ListChanged += new ListChangedEventHandler(districts_ListChanged);
        }

        static void Utility_AddingNew(object sender, AddingNewEventArgs e)
        {
            e.NewObject = new District();
            ((District)e.NewObject).Id = db.districts.Count + 1;
            //throw new NotImplementedException();
        }

        ////static void servers_AddingNew(object sender, AddingNewEventArgs e)
        ////{
        ////    e.NewObject = new Server();
        ////    ((Server)e.NewObject).Id = db.servers.Count + 1;
        ////}


        public static void SaveToDatabse()
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = new FileStream(DATABASE_PATH, FileMode.Create))
            {
                bf.Serialize(fs, db);
            }
        }

        static void LoadDatabase()
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs = new FileStream(DATABASE_PATH, FileMode.Open))
            {
                db = (Database)bf.Deserialize(fs);
            }
        }

        static void LoadLocalSettings() 
        {
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs=new FileStream(SETTINGS_PATH,FileMode.Open))
            {
                Setting = (PointSetting)bf.Deserialize(fs);
            }
        }

        public static void SaveLocalSettings() 
        {
            if (!Directory.Exists(@"D:\SBK\Backup\"))
            {
                Directory.CreateDirectory(@"D:\SBK\Backup\");
            }
            BinaryFormatter bf = new BinaryFormatter();
            using (FileStream fs =new  FileStream(SETTINGS_PATH,FileMode.Create))
            {
                bf.Serialize(fs, Setting);
            }
        }

        static void districts_ListChanged(object sender, ListChangedEventArgs e)
        {
            // MessageBox.Show("Test");
        }

        ////static void districts_AddingNew(object sender, AddingNewEventArgs e)
        ////{
        ////    e.NewObject = new District();
        ////    ((District)e.NewObject).Id = db.districts.Count + 1;
        ////    //throw new NotImplementedException();
        ////}




        //获取区县 网点 服务器 的绑定列表
        public static BindingList<District> GetDistricts()
        {
            return db.districts;
        }

        //public static BindingList<Point> GetPoints()
        //{
        //    return db.points;
        //}

        public static BindingList<Server> GetServers()
        {
            return db.servers;
        }


        public enum ServerType : int
        {
            DistrictUpdate = 2, DistrictApp = 1, CityUpdate = 5, CityApp = 4
        }

        public static BindingList<Server> GetServersByType(Enum serverType)
        {
            BindingList<Server> ret = new BindingList<Server>();
            foreach (var item in db.servers)
            {
                if (item.ServerType == serverType.GetHashCode())
                {
                    ret.Add(item);
                }
            }
            return ret;
        }

        public static BindingList<Point> GetPointsByDistrictId(int districtId)
        {


            //如果没有对应于districtid的points列表 那么新建一个
            if (!db.points.ContainsKey(districtId))
            {
                db.points.Add(districtId, new BindingList<Point>());
            }

            return db.points[districtId];

        }



        public static int GetDistrictIdByGatewayIP(string gatewayIP,out string pointCode)
        {

            foreach (int key in db.points.Keys)
            {
                BindingList<Point> subpoints;
                db.points.TryGetValue(key, out subpoints);

                foreach (var point in subpoints)
                {
                    if (point.GateWay.Equals(gatewayIP))
                    {
                        pointCode = point.PointCode;
                        return key;
                    }
                }


            }
            pointCode = string.Empty;
            return -1;

        }
    }


}
